/**
 * Copyright (C) 2025 pony working team
 * SPDX-License-Identifier: MulanPSL-2.0
 */

/* includes (local) ----------------------------------------------------------*/
#include <vlog_msg.h>
/* includes (standard library, system) ---------------------------------------*/
#include <string.h>
#include <ctype.h>
/* includes (other library) --------------------------------------------------*/
/* includes (project) --------------------------------------------------------*/

/* defines -------------------------------------------------------------------*/
/* typedefs ------------------------------------------------------------------*/
/* macro ---------------------------------------------------------------------*/
/* variables (extern) --------------------------------------------------------*/
/* variables (local) ---------------------------------------------------------*/
/* variables (global) --------------------------------------------------------*/
/* inlines -------------------------------------------------------------------*/
/* functions -----------------------------------------------------------------*/

static void print_indent(FILE *stream, int num)
{
    int i;

    for (i = 0; i < num; ++i) {
        fprintf(stream, "    ");
    }
}

/**
 * vlog_buffer - print buffer contents in message format
 *
 * uint8_t buffer[] = {
 *     1, 2, 3, 4, 43, 32, 1, 1, 144, 88, 4, 6, 7, 8, 9, 12,
 *     13, 14, 15, 16, 16, 235, 7, 8, 99, 54
 * };
 *
 * vlog_buffer(stdout, buffer, sizeof(buffer), 0);
 *
 * 01 02 03 04  2B 20 01 01  90 58 04 06  07 08 09 0C   ....+ ...X......
 * 0D 0E 0F 10  10 EB 07 08  63 36                      ........c6
 *
 * @stream: the file stream, like: stdout, stderr
 * @buf: the data buffer
 * @len: the length of buffer
 * @indent: the indent count (each indent is four space)
 *
 * @return NA
 */
void vlog_buffer(FILE *stream, const uint8_t *buf, int len, int indent)
{
    int i;

    if (len == 0) {
        fprintf(stream, "\n");
    }
    if (buf == NULL) {
        return;
    }

    i = 0;
    while (i < len) {
        uint8_t array[16];
        int j;

        print_indent(stream, indent);
        memcpy(array, buf + i, 16);
        for (j = 0; j < 16 && i + j < len; j++) {
            fprintf(stream, "%02X ", array[j]);
            if (j % 4 == 3) {
                fprintf(stream, " ");
            }
        }
        if (len > 16) {
            while (j < 16) {
                fprintf(stream, "   ");
                if (j % 4 == 3) {
                    fprintf(stream, " ");
                }
                j++;
            }
        }
        fprintf(stream, " ");
        for (j = 0; j < 16 && i + j < len; j++) {
            if (isprint(array[j])) {
                fprintf(stream, "%c", array[j]);
            } else {
                fprintf(stream, ".");
            }
        }
        fprintf(stream, "\n");
        i += 16;
    }
}
